package com.groupfour.attendancemanagementsystem.controller;

import com.groupfour.attendancemanagementsystem.service.AdminService;
import com.groupfour.attendancemanagementsystem.service.StudentService;
import com.groupfour.attendancemanagementsystem.service.TeacherService;
import com.groupfour.attendancemanagementsystem.utils.JwtHelper;
import com.groupfour.attendancemanagementsystem.utils.MD5;
import com.groupfour.attendancemanagementsystem.utils.Result;
import com.groupfour.attendancemanagementsystem.utils.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class UpdatePasswordController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    // 验证原密码是否正确
    @PostMapping("/oldPasswordIsTrue/{oldPassword}")
    public Result isTrue(
            @RequestHeader("token")String token,
            @PathVariable String oldPassword) {

        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        //从token中解析出用户密码
        String userPassword = JwtHelper.getUserPassword(token);

        String oldPwd = MD5.encrypt(oldPassword);

        if (userPassword.equals(oldPwd)) {
            return Result.ok().message("原密码正确");
        }
        return Result.fail().message("原密码错误");
    }


    @PostMapping("/updatePwd/{newPassword}")
    public Result updatePasswordByUserCode(
            @RequestHeader("token") String token,
            @PathVariable String newPassword
    ){
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            // token过期
            return Result.fail().message("token失效,请重新登录后修改密码");
        }

        // 从token中解析出 用户账号和用户的类型
        String userCode = JwtHelper.getUserCode(token);
        Integer userType = JwtHelper.getUserType(token);

        newPassword= MD5.encrypt(newPassword);

        int result = 0;
        switch (userType) {
            case 0:
                result = adminService.updatePassword(newPassword,userCode);
                break;
            case 1:
                result = studentService.updatePassword(newPassword,userCode);
                break;
            case 2:
                result = teacherService.updatePassword(newPassword,userCode);
                break;
        }
        if (result != 0) {
            return Result.ok().message("修改密码成功");
        } else {
            return Result.fail().message("修改密码失败");
        }
    }
}
